﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Diagnostics;

namespace SilverAnts.Utilities
{
    #region 系统环境
    /// <summary>
    /// 环境类
    /// </summary>
    public class EnvironmentExtern
    {
        public static string CPUName
        {
            get
            {
                RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0");
                object obj = rk.GetValue("ProcessorNameString");
                string CPUName = (string)obj;
                return CPUName.TrimStart();
            }
        }
        public static int CPUFrequency
        {
            get
            {
                RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0");
                object obj = rk.GetValue("~MHz");
                int CPUFrequency = (int)obj;
                return CPUFrequency;
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        public struct MEMORY_INFO
        {
            public uint dwLength;
            public uint dwMemoryLoad;
            public uint dwTotalPhys;
            public uint dwAvailPhys;
            public uint dwTotalPageFile;
            public uint dwAvailPageFile;
            public uint dwTotalVirtual;
            public uint dwAvailVirtual;
        }
        [DllImport("kernel32")]
        public static extern void GlobalMemoryStatus(ref MEMORY_INFO meminfo);

        public static string MemoryStatus
        {
            get
            {
                MEMORY_INFO MemInfo;
                MemInfo = new MEMORY_INFO();
                GlobalMemoryStatus(ref MemInfo);
                long totalMb = Convert.ToInt64(MemInfo.dwTotalPhys.ToString()) / 1024 / 1024;
                long avaliableMb = Convert.ToInt64(MemInfo.dwAvailPhys.ToString()) / 1024 / 1024;
                return avaliableMb + "/" + totalMb + " MB";
            }
        }

        public static string CPUStatus
        {
            get
            {
                const string CategoryName = "Processor";
                const string CounterName = "% Processor Time";
                const string InstanceName = "_Total";
                PerformanceCounter pc = new PerformanceCounter(CategoryName, CounterName, InstanceName);
                return pc.NextValue() + "%.";
            }
        }
    }
    #endregion
}
